package com.uxsino.commons.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class IO {
    public static Charset ENCODING = Charset.defaultCharset();

    public static ByteArrayOutputStream read(InputStream  in) throws IOException {
        if(in == null){
            return null;
        }
        byte[] cache = new byte[512];
        int count = 0;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((count = in.read(cache)) != -1){
            out.write(cache, 0, count);
        }
        return out;
    }

    public static String read(InputStream in, Charset charset) throws IOException {
        ByteArrayOutputStream out = read(in);
        if(out == null){
            return null;
        }
        return new String(out.toByteArray(), charset!=null?charset:ENCODING);
    }

    public static void write(InputStream in, OutputStream out) throws IOException{
        byte[] cache = new byte[1024];
        int len = -1;
        while ((len = in.read(cache)) != -1){
            write(cache, 0, len, out);
            out.flush();
        }
    }

    public static void write(byte[] data, OutputStream out) throws IOException {
        write(data, 0, data.length, out);
    }

    public static void write(byte[] data, int offset, int length, OutputStream out) throws IOException {
        out.write(data, offset, length);
        out.flush();
    }

    public static void write(String content, String charset, OutputStream out) throws IOException {
        write(content.getBytes(charset), out);
    }
}
